import React, { useEffect, useState } from "react"
import {
    Space,
    Form,
    Input,
    Select,
    Button,
    Tag,
    Icon,
    Radio
} from "@bytedance/mona-ui"
import InputColor from 'react-input-color';
import './DeteilCanvasStyle.scss'
import { dealImageData } from '../contents/jinritemaiCopyGoods/copyDataFomate'


const { TextArea } = Input;

let setCbTime

function redeConter(text = '', size = 12, sizeColor = '#000', bgColor = '#fff', align) {
    // console.log('text', text, size)
    let mycanvas = document.getElementById('userTextCanva') as HTMLCanvasElement
    var ctx: any = mycanvas.getContext("2d");
    ctx.fillRect(0, 0, mycanvas.width, mycanvas.height);
    let lenter = []
    const canvaText = {
        canvas: ctx,
        text,
        x: 15,
        y: 16,
        maxWidth: mycanvas.width - 20,
        lineHeight: 16,
        size,
        color: sizeColor,
        lenteerr: size / 2
    }
    ctx.font = size + "px Verdana"
    lenter = getWarpText(canvaText)

    mycanvas.height = lenter.length * (canvaText.y + canvaText.lenteerr) + canvaText.y / 2

    // 设置画布颜色
    ctx.fillStyle = bgColor
    // 填充全部
    ctx.fillRect(0, 0, mycanvas.width, mycanvas.height);


    for (let i = 0; i < lenter.length; i++) {
        const item: any = lenter[i];
        ctx.fillStyle = canvaText.color
        ctx.font = size + "px Verdana"
        let heiteri = ctx.measureText(item.text);
        const alignData = {
            center: (mycanvas.width - heiteri.width) / 2,
            left: item.x,
            right: mycanvas.width - heiteri.width - item.x
        }
        ctx.fillText(item.text, alignData[align] || alignData.left, item.y);

    }
    let canvas2 = document.createElement("canvas")
    canvas2.width = mycanvas.width;
    canvas2.height = mycanvas.height;
    let ctx2: any = canvas2.getContext("2d");
    let imageData = ctx.getImageData(0, 0, mycanvas.width, mycanvas.height);
    let imgData2 = dealImageData(imageData);
    ctx2.putImageData(imgData2, 0, 0);
    return canvas2.toDataURL("image/jpeg", 1)
}
function getWarpText(canvaData) {
    let { canvas, text, x, y, maxWidth, lineHeight, lenteerr } = canvaData
    y += lenteerr
    // 对入参的类型进行检测
    if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number' || typeof lineHeight != 'number') {
        throw new Error("参数传入出错")
    }

    let arrText = text.split('');
    let line = '';
    let lines: any = [];
    let lastLine = ""

    for (let n = 0; n < arrText.length; n++) {
        if (arrText[n] == '\n') {
            lines.push({
                text: line,
                x: x,
                y: y
            })
            line = arrText[n];
            y += (lineHeight + lenteerr);
        } else {
            //每个循环累加字符
            let testLine = line + arrText[n];
            //检测累加字符 获取累加字符的高度和宽度
            let metrics = canvas.measureText(testLine);
            let testWidth = metrics.width;
            // let lineWidth = canvas.measureText(line).width;


            if (testWidth > maxWidth && n > 0) {
                lastLine = line;
                lines.push({
                    text: line,
                    x: x,
                    y: y
                })
                line = arrText[n];
                y += (lineHeight + lenteerr);
            } else {
                line = testLine;
            }
        }

    }
    if (lastLine !== line) {
        lines.push({
            text: line,
            x: x,
            y: y
        })
    }

    // canvas.height = 100
    return lines;
}
// let key
function SetCanvasType(props) {
    const { onChangeUrl, searchWord, configStatus, onChangeConfig } = props
    // {
    //     Textplaceholder: '请输入文本内容',
    //     TextValue: '',
    //     fontSize: 16,
    //     sizeColor: '#000000',
    //     bgColor: '#ffffff',
    //     align: 'left'
    // }
    const [ifromContent, setIfromContent] = useState(configStatus)
    useEffect(() => {
        if (JSON.stringify(configStatus) !== JSON.stringify(ifromContent)) {
            setIfromContent({ ...configStatus })
        }
    }, [configStatus])

    useEffect(() => {
        const getUrl = redeConter(ifromContent.TextValue || ifromContent.Textplaceholder, ifromContent.fontSize, ifromContent.sizeColor, ifromContent.bgColor, ifromContent.align)
        // console.log('ifromContent修改', ifromContent)
        // console.log('getUrl', getUrl)
        onChangeUrl && onChangeUrl(getUrl)
        if (setCbTime) return
        setCbTime = setTimeout(() => {
            clearTimeout(setCbTime)
            setCbTime = null
        }, 100)
        onChangeConfig && onChangeConfig({ ...ifromContent, betUrl: getUrl })
    }, [ifromContent]);
    // console.log('热搜词', searchWord)
    let isAddList: number[] = []
    let addContent: string[] = []
    const [shearWorders, setShearWorders] = useState<any>(getTitleRefoter())
    // console.log('shearWorders', shearWorders)
    function getTitleRefoter() {
        // console.log('searchWord', searchWord)
        if (!searchWord || searchWord.length < 20) {
            return []
        }
        // return []

        const miyer: number = Math.floor(Math.random() * searchWord.length)
        if (!isAddList.includes(miyer)) {
            const strs = searchWord[miyer].cell_info?.query.query_value.value.value_str
            let interCount = strs.replace(/[^\x00-\xff]/g, "aa").length
            let interlength = addContent.join('').replace(/[^\x00-\xff]/g, "aa").length
            let outInterlength = 100 - interlength
            if (outInterlength >= interCount) {
                addContent.push(searchWord[miyer].cell_info.query.query_value.value.value_str)
                isAddList.push(miyer)
                getTitleRefoter()
            }
        } else {
            getTitleRefoter()
        }
        return addContent
    }
    return (<div>
        <div className="conter">
            文本
        </div>
        <div className="congterironbox">
            <Form layout="vertical">
                <Form.Item
                    // name="Input"
                    label="文本内容">
                    <Space direction="vertical" style={{
                        width: '100%'
                    }}>
                        <TextArea autoSize={{ minRows: 2, maxRows: 6 }} limit={1000} placeholder={ifromContent.Textplaceholder} value={ifromContent.TextValue} onChange={(e) => {
                            // console.log('e.target.value', e.target.value)
                            setIfromContent({
                                ...ifromContent,
                                TextValue: e.target.value
                            })
                        }}></TextArea>
                        {(shearWorders && shearWorders.length) && <div>
                            <Button type="link" icon={<Icon type="RefreshIcon" />} onClick={(e) => {
                                // console.log('eee添加')
                                isAddList = []
                                addContent = []
                                const refodater = getTitleRefoter()
                                setShearWorders(JSON.parse(JSON.stringify(refodater)))
                                // console.log('refodater', refodater)
                                // refoConterDataAi[index].cuts = refodater
                                // setRefoConterData([...refoConterData])
                            }}>刷新</Button>
                            <Tag color="#000" type="success">
                                热搜词
                            </Tag>
                            {shearWorders?.map((titel, keys) => {
                                return <Tag bordered type="default" key={keys} style={{
                                    cursor: 'pointer',
                                    // textWrap: 'nowrap'
                                }}
                                >
                                    <span onClick={() => {
                                        setIfromContent({
                                            ...ifromContent,
                                            TextValue: ifromContent.TextValue + titel
                                        })
                                    }}>
                                        {titel}
                                    </span>

                                </Tag>
                            })}
                        </div>}
                        <Button size="mini" type="primary" onClick={() => {
                            setIfromContent({
                                ...ifromContent,
                                TextValue: ifromContent.TextValue + shearWorders?.join('')
                            })
                        }}>添加全部</Button>
                    </Space>

                </Form.Item>
                <Form.Item
                    // name="Input"
                    label="字号">
                    <Select value={ifromContent.fontSize} onChange={(e: any) => {
                        setIfromContent({
                            ...ifromContent,
                            fontSize: e
                        })
                    }}>
                        <Select.Option value={13}>13</Select.Option>
                        <Select.Option value={14}>14</Select.Option>
                        <Select.Option value={15}>15</Select.Option>
                        <Select.Option value={17}>17</Select.Option>
                        <Select.Option value={20}>20</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item
                    // name="Input"
                    label="字体颜色">
                    <Space align="center" className="alyerConter">
                        <Input value={ifromContent.sizeColor} onChange={(e) => {
                            setIfromContent({
                                ...ifromContent,
                                sizeColor: e.target.value
                            })
                        }} />
                        <InputColor
                            initialValue={ifromContent.sizeColor}
                            onChange={(e: any) => {
                                setIfromContent({
                                    ...ifromContent,
                                    sizeColor: e.hex
                                })
                            }}
                            placement="left"
                        />
                    </Space>

                </Form.Item>
                <Form.Item
                    // name="Input"
                    label="背景颜色">
                    <Space align="center" className="alyerConter">
                        <Input value={ifromContent.bgColor} onChange={(e) => {
                            setIfromContent({
                                ...ifromContent,
                                bgColor: e.target.value
                            })
                        }} />
                        <InputColor
                            initialValue={ifromContent.bgColor}
                            onChange={(e: any) => {
                                setIfromContent({
                                    ...ifromContent,
                                    bgColor: e.hex
                                })
                            }}
                            placement="left"
                        />
                    </Space>

                </Form.Item>
                <Form.Item
                    // name="Input"
                    label="对齐方式">
                    <Space>
                        <Button type={ifromContent.align == 'left' ? 'dashed' : 'default'} onClick={() => {
                            setIfromContent({
                                ...ifromContent,
                                align: 'left'
                            })
                        }}>左对齐</Button>
                        <Button type={ifromContent.align == 'center' ? 'dashed' : 'default'} onClick={() => {
                            setIfromContent({
                                ...ifromContent,
                                align: 'center'
                            })
                        }}>居中对齐</Button>
                        <Button type={ifromContent.align == 'right' ? 'dashed' : 'default'} onClick={() => {
                            setIfromContent({
                                ...ifromContent,
                                align: 'right'
                            })
                        }}>右对齐</Button>
                    </Space>
                </Form.Item>
            </Form>
        </div>

    </div>)


}


function DeteilCanvas(props) {
    const { onChangeUrl, searchWord, openIndex, copynum = 1, onChangeUrlAll } = props
    const [addAllContentText, setAddAllContentText] = useState<any[]>(openIndexFunSets())
    const [selectIndex, setSelectIndex] = useState(0)
    function openIndexFunSets() {
        // if (openIndex && openIndex == 'ALL') {
        let addPncyer: any = []
        for (let i = 0; i < copynum; i++) {
            addPncyer.push({
                Textplaceholder: '请输入文本内容',
                TextValue: '',
                fontSize: 16,
                sizeColor: '#000000',
                bgColor: '#ffffff',
                align: 'left',
                betUrl: ''
            })
        }
        return addPncyer
        // }
    }
    return (<div className="moter">
        <Space style={{
            width: '100%',
            justifyContent: 'space-between',
            height: '100%',
        }}
            className="DeteilCanvasBox"
        >

            <div className="leftBox" style={{
                height: '100%',

            }}>
                <div className="conterToyer">
                    <canvas width={375} height={0} id='userTextCanva'></canvas>
                </div>
            </div>
            <div className="setStatus" style={{
                height: '100%',
                width: '100%',
                overflowY: "scroll"
            }}>
                <SetCanvasType
                    onChangeUrl={onChangeUrl}
                    searchWord={searchWord}
                    configStatus={addAllContentText[selectIndex]}
                    onChangeConfig={(e) => {
                        addAllContentText[selectIndex] = e
                        setAddAllContentText([...addAllContentText])
                        onChangeUrlAll && onChangeUrlAll(addAllContentText)
                        console.log(e)
                    }} />
            </div>
        </Space>
        {openIndex && openIndex === 'ALL' && <div className="conterbox">
            <Radio.Group value={selectIndex} size="small" onChange={(e) => {
                console.log('eeee', e)
                setSelectIndex(e.target.value)
            }}>
                {addAllContentText.map((res, index) => {
                    return <Radio.Button key={index} value={index}>链接 {index + 1} 详情图</Radio.Button>
                })}
            </Radio.Group>
        </div>}


    </div>
    )
}

export default DeteilCanvas